package web.beans;

import Weather.Forecast;
import util.HttpRequests;

import javax.faces.event.ValueChangeEvent;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Serializable;

/**
 * Created by vanches on 4.1.15.
 */
public class WeatherBean implements Serializable {

    private String cities;
    private Forecast forecast;
    private final String  yandexWather="http://export.yandex.ru/weather-ng/forecasts/";

    public void citiesSet(ValueChangeEvent e) {

        cities = e.getNewValue().toString();
        downloaderWeather();

    }

    private void downloaderWeather(){
        String xml=null;
        HttpRequests httpRequests=new HttpRequests();
        try {
            xml=httpRequests.sendGet(cities,yandexWather);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        InputStream pStm = new ByteArrayInputStream(xml.getBytes());
        //JAXBContext jaxbContext = null;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(Forecast.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            forecast = (Forecast) jaxbUnmarshaller.unmarshal(pStm);
        } catch (JAXBException e1) {
            e1.printStackTrace();
        }
    }
    //region GET and SET

    public String getCities() {
        return cities;
    }

    public void setCities(String cities) {
        this.cities = cities;
    }

    public Forecast getForecast() {
        return forecast;
    }
//endregion
}

